package zeroj.web.interceptors;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import zeroj.web.core.Interceptor;

/**
 * 
 * 
 * @author lyl(lylsir at gmail dot com)
 * 
 * @since 1.0
 * 
 * 2008-9-10
 */
public class InterceptorFactory {

	private static final Log log = LogFactory.getLog(InterceptorFactory.class);
	private Map<Class<? extends Interceptor>, Interceptor> interceptors =
		new HashMap<Class<? extends Interceptor>, Interceptor>();
	private ReadWriteLock lock = new ReentrantReadWriteLock();
	private static InterceptorFactory instance = new InterceptorFactory();
	
	public static Interceptor getInterceptor(Class<? extends Interceptor> clz) {
		
		Interceptor interceptor = null;
		instance.lock.readLock().lock();
		try {
			interceptor = instance.interceptors.get(clz);
		} finally {
			instance.lock.readLock().unlock();
		}
		if(interceptor == null) {
			interceptor = instance.newInterceptor(clz);
		}
		return interceptor;
	}
	
	private Interceptor newInterceptor(Class<? extends Interceptor> clz) {
		
		Interceptor interceptor = null;
		lock.writeLock().lock();
		try {
			interceptor = instance.interceptors.get(clz);
			if(interceptor == null) {
				interceptor = clz.newInstance();
				interceptors.put(clz, interceptor);
			} 
		} catch (Exception e) {
			log.warn("Cannot instance interceptor " + clz);
		} finally {
			lock.writeLock().unlock();
		}
		return interceptor;
		
	}
	
}
